import {
    Card,
    Space,
    Button,
    Form,
    Input,
    Table,
    Spin,
    notification,
} from 'antd'
import { useRef, useState, useEffect } from 'react'
import CommonDialog from '@/components/commonDialog'
import FormConfig from './components/formConfig'
import { DetailConfig } from './components/detailConfig'
import { getColumns } from './components/tableColumns'
import { getDealerlistApi } from '@/api/dealer'
import { orginList, productList, detailInfo } from './components/data'
import { formatNumberWithCommas } from '@/utils/common'
import dayjs from 'dayjs'
import React from 'react'
export default function ComputedValue() {
    const [form] = Form.useForm()
    const formRef = useRef<any>(null)
    const [dialogOpen, setDialogOpen] = useState(false)
    const [dialogContent, setDialogContent] = useState(false)
    const [confirmLoading, setConfirmLoading] = useState(false)
    const [title, setTitle] = useState('新建申报单')
    const [dataSource, setDataSource] = useState([])
    const [total, setTotal] = useState(0)
    const [loading, setLoading] = React.useState<boolean>(false)
    const [tableParams, setTableParams] = useState({
        pagination: {
            current: 1,
            pageSize: 10,
        },
    })
    const dealerColumns = {
        '1': '待审核',
        '2': '已撤销',
        '3': '审核失败',
        '4': '待申报',
        '5': '申报成功',
    }
    function fetchData(values = {}) {
        const pageData = {
            page: tableParams.pagination?.current,
            pageSize: tableParams.pagination?.pageSize,
            ...values,
        }
        setLoading(true)
        getDealerlistApi(pageData)
            .then((res: any) => {
                const result = res.data.map((item: any, index) => {
                    item.key = index // 使用索引作为key，或者使用item.id等唯一标识
                    item.status =
                        dealerColumns[item.status as keyof typeof dealerColumns]
                    return { ...item }
                })
                setDataSource(result)
                setTotal(res.total)
            })
            .finally(() => {
                setLoading(false)
            })
    }
    useEffect(() => {
        fetchData()
    }, [tableParams])

    // 新增操作，打开弹窗并设置内容
    const handleAdd = () => {
        // setDialogContent(`你正在编辑：${name}`)
        setDialogOpen(true)
    }
    // 编辑操作，打开弹窗并设置内容
    const handleEdit = (record: any) => () => {
        setTitle('编辑用户')
        setDialogOpen(true)
        // 等待弹窗打开后，再设置表单数据
        setTimeout(() => {
            const data = {
                orgin: ['1000', '1001', '1002'],
                date: dayjs('2025-11-20'),
                product: ['productA'],
                dealer: 2,
                chooseDealer: [
                    {
                        id: 4,
                        username: '刘镇闻',
                    },
                    {
                        id: 3,
                        username: '春华',
                    },
                ],
            }
            formRef.current?.setFieldsValue(data)
        }, 0)
    }
    // 删除操作
    const handleDelete = (key: React.Key) => {
        // 这里可以调用删除接口，删除成功后重新获取数据
        deleteUserApi({ id: key }).then((res) => {
            const config = {
                message: '',
                description: res.message,
                duration: 2,
            }
            notification.success(config)
            fetchData()
        })
    }
    // 详情操作，打开弹窗并设置内容
    const handleDetail = (record: any) => () => {
        setTitle('申报详情')
        // setDialogContent(true)
        setLoading(true)
        setTimeout(() => {
            try {
                const data = [
                    {
                        key: '1',
                        children: '1234567890',
                    },
                    {
                        key: '2',
                        label: '申报截止时间',
                        children: '2025-12-31',
                    },
                    {
                        key: '3',
                        label: '申报状态',
                        children: '1', // 1-待审核, 2-已撤销, 3-审核失败, 4-待申报, 5-申报成功
                    },
                    {
                        key: '4',
                        label: '经销商数量',
                        children: 5000,
                    },
                    {
                        key: '5',
                        label: '申报SKU种类',
                        children: '2',
                    },
                    {
                        key: '6',
                        label: '申报数量',
                        children: 10000,
                    },
                ]
                // 如果data的key和detailInfo的key对应，可以直接用data的children赋值detailInfo的children
                if (Array.isArray(detailInfo)) {
                    data.forEach((item) => {
                        const found = detailInfo.find((d) => d.key === item.key)
                        if (found) {
                            if (
                                item.children &&
                                typeof item.children === 'number'
                            ) {
                                console.log('found.children', found.children)
                                // 如果是数字类型，可以进行格式化处理 展示千分符
                                found.children = formatNumberWithCommas(
                                    item.children
                                )
                                return
                            }
                           found.children = item.children 
                        }
                    })
                }
                console.log('detailInfo', detailInfo)
                setLoading(false)
                setDialogContent(true)
            } catch (error) {}
        }, 2000)
    }
    // 弹窗确定按钮，触发表单校验
    const handleDialogOk = async () => {
        console.log('formRef.current', formRef.current)
        if (formRef.current) {
            setConfirmLoading(true)
            try {
                // 获取表单数据
                const values = await formRef.current.submit()
                const payload = {
                    ...values,
                    date: values.date
                        ? dayjs(values.date).format('YYYY-MM-DD')
                        : undefined,
                }
                console.log('表单数据：', payload)
            } catch (e) {
                console.log('表单校验失败：', e)
                // setDialogOpen(false)
                setConfirmLoading(false)
            }
        }
    }

    const handleDialogCancel = () => {
        // 重置表单
        formRef.current?.reset()
        setDialogOpen(false)
    }
    const handleDetailCancel = () => {
        // 重置表单
        // formRef.current?.reset()
        setDialogContent(false)
    }
    const handleQuery = () => {
        // 获取表单值
        const values = form.getFieldsValue()
        // 这里可以根据实际情况进行数据请求
        fetchData(values)
    }
    const resetForm = () => {
        form.resetFields()
        fetchData()
    }
    return (
        <>
            <Spin spinning={loading}>
                <Space
                    direction="vertical"
                    style={{ width: '100%' }}
                    size="middle"
                >
                    <Card>
                        <Form layout="inline" form={form} initialValues={{}}>
                            <Form.Item label="申报单编号：" name="name">
                                <Input placeholder="" />
                            </Form.Item>
                            <Form.Item label="申报大区：" name="region">
                                <Input placeholder="" />
                            </Form.Item>
                            <Form.Item label="申报状态：" name="status">
                                <Input placeholder="" />
                            </Form.Item>
                            <Form.Item>
                                <Space>
                                    <Button
                                        type="primary"
                                        onClick={handleQuery}
                                    >
                                        查询
                                    </Button>
                                    <Button onClick={resetForm}>重置</Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Card>
                    <Space align="center">
                        <Button type="primary" onClick={() => handleAdd()}>
                            新建
                        </Button>
                    </Space>
                    <Table
                        bordered
                        columns={getColumns(
                            handleDelete,
                            handleEdit,
                            handleDetail
                        )}
                        dataSource={dataSource}
                        // scroll={{ x: 1200 }}
                        scroll={{ x: 'max-content' }}
                        pagination={{
                            current: tableParams.pagination?.current,
                            pageSize: tableParams.pagination?.pageSize,
                            total, // 确保有 total
                            showSizeChanger: true,
                            showQuickJumper: true,
                            showTotal: () => `共 ${total} 条`,
                            onChange: (page, pageSize) => {
                                setTableParams({
                                    ...tableParams,
                                    pagination: {
                                        ...tableParams.pagination,
                                        current: page,
                                        pageSize,
                                    },
                                })
                                // 这里可以触发数据请求
                            },
                        }}
                    />
                </Space>
                <CommonDialog
                    open={dialogOpen}
                    title={title}
                    width={1400}
                    confirmLoading={confirmLoading}
                    onOk={handleDialogOk}
                    onCancel={handleDialogCancel}
                >
                    <FormConfig
                        ref={formRef}
                        orginList={orginList}
                        productList={productList}
                    />
                </CommonDialog>
                <CommonDialog
                    open={dialogContent}
                    title={title}
                    width={1400}
                    confirmLoading={confirmLoading}
                    onCancel={handleDetailCancel}
                >
                    <DetailConfig
                        detailInfo={detailInfo}
                        dialogContent={dialogContent}
                    />
                </CommonDialog>
            </Spin>
        </>
    )
}
